package com.ruoyi.system.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.vo.RcHtmlVo;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.RcHtml;
import com.ruoyi.system.service.IRcHtmlService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import oshi.util.Util;

/**
 * 内容Controller
 *
 * @author ruoyi
 * @date 2023-07-27
 */
@RestController
@RequestMapping("/basic/web")
public class RcHtmlController extends BaseController
{
    @Autowired
    private IRcHtmlService rcHtmlService;

    /**
     * 校验字符串数组是否只包含数字、字母和逗号
     * 空数组返回 true
     * @param cateList 输入的字符串数组
     * @return 如果所有字符串都符合要求，返回 true；否则返回 false
     */
    public static boolean validateCateList(String[] cateList) {
        if (cateList == null || cateList.length == 0) {
            return true; // 空数组或 null 视为合法
        }

        // 正则表达式：只允许数字、字母和逗号
        String regex = "^[a-zA-Z0-9,\\$\\-]+$";

        // 遍历数组，校验每个字符串
        for (String item : cateList) {
            if (!item.matches(regex)) {
                return false; // 如果某个字符串不符合要求，返回 false
            }
        }
        return true; // 所有字符串都符合要求
    }

    @GetMapping("/filter")
    public TableDataInfo filter(RcHtml rcHtml)
    {
        ArrayList<String> arr = rcHtmlService.filterCate(rcHtml);
        if(arr.size()>0){
            rcHtml.setCateList(arr.toArray(new String[arr.size()]));
        }
        startPage();
        List<RcHtml> list = rcHtmlService.selectRcHtmlList(rcHtml);
        return getDataTable(list);
    }

    /**
     * 检索内容列表
     */
    @GetMapping("/search")
    public TableDataInfo search(RcHtml rcHtml) throws UnsupportedEncodingException
    {
        String search = rcHtml.getSearch();
        if(StringUtils.isNotNull(search)){
            rcHtml.setSearchTxt(URLEncoder.encode(search, "UTF-8").replace("%","\\%"));
        }
        startPage();
        List<RcHtml> list = rcHtmlService.searchRcHtmlList(rcHtml);
        return getDataTable(list);
    }

    /**
     * 导出内容列表
     */
    //@PreAuthorize("@ss.hasPermi('system:html:export')")
    @Log(title = "内容", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RcHtml rcHtml)
    {
        List<RcHtml> list = rcHtmlService.selectRcHtmlList(rcHtml);
        ExcelUtil<RcHtml> util = new ExcelUtil<RcHtml>(RcHtml.class);
        util.exportExcel(response, list, "内容数据");
    }

    /**
     * 获取内容详细信息
     */
    //@PreAuthorize("@ss.hasPermi('system:html:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(rcHtmlService.selectRcHtmlById(id));
    }

    /**
     * 新增内容
     */
    //@PreAuthorize("@ss.hasPermi('system:html:add')")
    @Log(title = "内容", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RcHtml rcHtml)
    {
        rcHtml.setCreateBy(getUsername());
        return toAjax(rcHtmlService.insertRcHtml(rcHtml));
    }

    /**
     * 修改内容
     */
    //@PreAuthorize("@ss.hasPermi('system:html:edit')")
    @Log(title = "内容", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RcHtml rcHtml)
    {
        rcHtml.setUpdateBy(getUsername());
        return toAjax(rcHtmlService.updateRcHtml(rcHtml));
    }

    /**
     * 删除内容
     */
    //@PreAuthorize("@ss.hasPermi('system:html:remove')")
    @Log(title = "内容", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(rcHtmlService.deleteRcHtmlByIds(ids));
    }


    /**
     * 查询内容列表
     * TODO 定制接口优化：内容返回做到单个查询（列表用不到内容，增加交互效率）
     */
    @GetMapping("/list")
    public TableDataInfo list(RcHtml rcHtml)
    {
        List<RcHtml> list = null;
        if(validateCateList(rcHtml.getCateList())){
            startPage();
            list = rcHtmlService.selectRcHtmlList(rcHtml);
        }
        TableDataInfo res = getDataTable(list);
        res.setRows(PageUtils.convertList(list,RcHtmlVo.class));
        return res;
    }

    /**
     * 获取内容详细信息
     */
    @GetMapping(value = "/detail")
    public AjaxResult getDetail(RcHtml rcHtml)
    {

        RcHtml obj = rcHtmlService.selectRcHtml(rcHtml);
        RcHtmlVo res = PageUtils.convertObject(obj,RcHtmlVo.class);
        return success(res);
    }

}
